package team.gl.nio.cln;

import java.awt.Color;
import java.text.SimpleDateFormat;
import java.util.Vector;
import java.util.concurrent.TimeUnit;

import com.richman.controller.BetClient;

import com.richman.ps38.PS38Thread;
import com.richman.ps38.entity.BetDvalue;
import com.richman.ps38.entity.Event;
import com.richman.ps38.entity.SendData;
import com.richman.utils.Common;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import team.gl.nio.cmn.Bag;
import team.gl.nio.cmn.NewBag;

public class ClientHandler extends ChannelInboundHandlerAdapter {  
	
	long lastreconnecttime = 0;
	
	
	
	public static ChannelHandlerContext ctx_s = null;	
	
	SimpleDateFormat dfSec = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override  
    public void channelRead(ChannelHandlerContext ctx, Object msg)  
            throws Exception {
    	
    	
    	
    	if(BetClient.betType == 0) {
        	NewBag us = (NewBag)msg;
        	
           	if(us.getReq().equals("bdvalues")){
            		BetClient.mainWnd.updateMainWndStatusText(1, "CLN与服务器连接正常");
            			if(BetClient.mainWnd != null && BetClient.betCtrMng != null && us != null) {
            				System.out.println(dfSec.format(System.currentTimeMillis()) + ":In BDP阶段");
            				BetClient.mainWnd.updateBetDvalueTable(us.getBdvalues());
            				System.out.println(dfSec.format(System.currentTimeMillis()) + ":Out BDP阶段");
            			}

            		}
    	}else if(BetClient.betType == 1) {
        	Bag us = (Bag)msg;
        	
           	if(us.getReq().equals("specialPankougames")){
            		BetClient.mainWnd.updateMainWndStatusText(1, "CLN与服务器连接正常");
            		if(BetClient.betCtrMng != null) {
        				BetClient.betCtrMng.updateBetCentralTable(us.senddatas);
        			}

            		}
    	}
    	

    		
    		
    	}
   
	@Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("--- Server is active ---");
        ctx_s = ctx;
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("--- Server is inactive ---");
        NettyClient.channel = null;
        // 10s 之后尝试重新连接服务器
        System.out.println("2s 之后尝试重新连接服务器...");
        
        
        
        NettyClient.group.schedule(new Runnable() {  
            
            @Override  
          
            public void run() {  
                while(NettyClient.connect() == false) {
                	
                	try{  					
    					Thread.sleep(5000);
    					
    				}catch(Exception e){
    					e.printStackTrace();
    				} 
                }
                System.out.println("重新连接成功");
            }  
          
          }, 200L, TimeUnit.MILLISECONDS);  
          
        super.channelInactive(ctx);
    }

}